Subclassing Python's type type
In my last post I checked out the type()
function with three parameters, which dynamically creates new classes. Now I wonder what happens when you use it to create a subclass of the class type
. By the way, you can also use the boring class A(...):
syntax to achieve the same thing.
I also can’t think of any practical use for this 😅:
new_type = type("new_type", (type,), {})
As expected, the new type has the following properties. It is not the same as type
, it is a subclass of type
and an instance of type
:
>>> new_type == type
False
>>> isinstance(new_type, type)
True
>>> issubclass(new_type, type)
True
Futhermore, both are really just types:
>>> type(new_type) == type(type) == type
True
And the new_type
type also acts as a function that creates new classes:
>>> new_str = new_type("new_str", (str,), {})
>>> type(new_str)
<class '__main__.new_type'>
>>> type(new_str) == type
False
>>> type(new_str) == new_type
True
OK, my brain hurts, let’s stop this madness.